package com.icez.base_util_library

import android.os.CountDownTimer
import android.os.Handler

/**
 *  定时器
 */
class TimerUtil {
    companion object{
        val instance:TimerUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            TimerUtil()
        }
    }

    /**
     *  倒计时 ，开始调用使用start，页面销毁的时间请记得移除
     * @param totalTime 总时间,毫秒
     * @param stepTime 间隔时间,毫秒
     * @param onCountDownFinishListener 倒计时完成回调
     */
    public fun countDownTime(totalTime:Long,stepTime:Long,onCountDownListener:((timeTemaining:Long)->Unit)?=null,onCountDownFinishListener:(()->Unit)?=null): CountDownTimer {
        val mCountDownTimer = object: CountDownTimer(totalTime,stepTime){
            override fun onTick(p0: Long) {
                var timeTemaining:Long = 0
                if(p0%stepTime>0){
                    timeTemaining = p0/stepTime + 1
                }else{
                    timeTemaining = p0/stepTime
                }
                if (onCountDownListener != null) {
                    onCountDownListener(timeTemaining)
                }
            }

            override fun onFinish() {
                if (onCountDownFinishListener != null) {
                    onCountDownFinishListener()
                }
            }

        }
        return mCountDownTimer
    }

    /**
     *  计时器 ,调用前请先调用timeHandler.removeCallbacks(timeHandler) ,在业务销毁的时间记得移除
     * @param timeHandler var timeHandler:Handler = Handler(Looper.getMainLooper())
     * @param stepTime 间隔时间,毫秒
     */
    public fun countUpTime(timeHandler: Handler, stepTime:Long, onCountUpListener:((currentTime:Long)->Unit)?=null): Runnable {
        var currentTime:Long = 0
        val timeRunnable:Runnable = object:Runnable{
            override fun run() {
                timeHandler.postDelayed(this, stepTime)
                currentTime++
                if (onCountUpListener != null) {
                    onCountUpListener(currentTime)
                }
            }

        }
        timeHandler.post(timeRunnable)
        return timeRunnable
    }

    /**
     *  计时器 ,调用前请先调用timeHandler.removeCallbacks(timeHandler) ,在业务销毁的时间记得移除
     * @param timeHandler var timeHandler:Handler = Handler(Looper.getMainLooper())
     * @param stepTime 间隔时间,毫秒
     */
    public fun countUpTime(timeHandler: Handler, onCountUpHourMinuteSecondListener:((totalSecond:Long,hour:Long, minute:Long, second:Long)->Unit)?=null): Runnable {
        return countUpTime(timeHandler,1000,onCountUpListener={
            LogUtil.E("计时器："+it)
            var lsSecond = it
            var hour:Long = 0
            var minute:Long = 0
            var second:Long = 0

            second = lsSecond%60
            minute = lsSecond/60%60
            hour = lsSecond/3600

            if (onCountUpHourMinuteSecondListener != null) {
                onCountUpHourMinuteSecondListener(lsSecond,hour,minute,second)
            }

        })
    }

}